Colin Pistell
9/17/2015
Branching logic and looping are the heart and soul of coding. It's basically why coding is 'useful'. If you understand these two things you can code just about anything…
The basic idea of branching logic is we may want different things to happen under different circumstances.
areTherePiranhas <- TRUE
if(areTherePiranhas == TRUE) {
print("Maybe I'll stay out of the lake...")
} else {
print("Woohoo! Time to swim!")
}
[1] "Maybe I'll stay out of the lake..."
areTherePiranhas <- FALSE
areThereSnakes <- TRUE
if (areTherePiranhas == TRUE) {
print("Maybe I'll stay out of the lake...")
} else if(areThereSnakes == TRUE) {
print("Snakes... why'd it have to be snakes...")
} else {
print("Woohoo! Time to swim!")
}
[1] "Snakes... why'd it have to be snakes..."
x <- 1
if(x < 2) {
print("duck 1")
} else if( x < 5) {
print("duck 2")
} else {
print("goose!")
}
[1] "duck 1"
Looping allows us to execute the same piece of code over each element in a collection of things
Consider this example:
x <- 1:3 #x is now a vector of 1,2,3
for(i in x) {
print(i + 1)
}
[1] 2
[1] 3
[1] 4
x <- 1:3
for(i in x) {
print("foo")
}
[1] "foo"
[1] "foo"
[1] "foo"
tacoTruckInventory <- 5
for(taco in 1:tacoTruckInventory) {
print("<burp> Yum!")
}
[1] "<burp> Yum!"
[1] "<burp> Yum!"
[1] "<burp> Yum!"
[1] "<burp> Yum!"
[1] "<burp> Yum!"
Take a look at the next two loops. What will their output be?
fruits <- c("apples", "mangos", "grapes")
for(i in fruits) {
print(paste("I like", i))
}
for(i in 1:length(fruits)) {
print(paste("I like", fruits[i]))
}
They result in the same output. The only difference is that in the second example “i” was set to the index of the object in the vector instead of the object itself.
Recall that each object in a vector has an index value:
fruits[1]
[1] "apples"
fruits[length(fruits)]
[1] "grapes"
So why loop via index? Isn't it needlessly complicated?
Let's say we want to find the squares of a vector of numbers and save the output to a new vector. We could do this:
toSquare <- c(2, 4, 6)
answers <- NULL #we need to initialize our answer vector
for(i in toSquare) {
answers <- c(answers, i^2)
}
answers
[1] 4 16 36
The previous example works, but there are some problems
Let's try again but this time loop via index…
toSquare <- c(2, 4, 6)
answers <- rep(NA, length(toSquare)) #instantly create a vector of the correct size
for(i in 1:length(toSquare)) {
answers[i] <- toSquare[i]^2
}
answers
[1] 4 16 36
toSquare <- c(2, 4, 6)
thatWasEasy <- toSquare^2
thatWasEasy
[1] 4 16 36
for(i in 1:length(fruits)) {
if(i < 3) {
print(paste("Yum, ", fruits[i], "!", sep = ""))
} else {
print("I'm full...")
}
}
[1] "Yum, apples!"
[1] "Yum, mangos!"
[1] "I'm full..."